<template>
  <div id="map-container"></div>
</template>

<script setup lang="ts">
  import {
    onMounted,
    onUnmounted,
    withDefaults,
    defineProps,
    watch,
  } from 'vue';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { initMapFile } from '@/utils/initMap';

  interface Props {
    lineArr?: number[][];
    defautStatus?: boolean;
  }
  const props = withDefaults(defineProps<Props>(), {
    lineArr: () => {
      return [];
    },
  });

  let map: any = null;
  let lineArrLocal: number[][] = [];
  let curMaker: any = null;
  let passedPolyline: any = null;
  let polyline: any = null;

  const setLineAni = (_lineArr: number[][]) => {
    if (!_lineArr.length) {
      _lineArr = [[116.478935, 39.997761]];
    }
    window.AMap.plugin('AMap.MoveAnimation', () => {});

    if (!map) {
      map = new window.AMap.Map('map-container', {
        resizeEnable: true,
        center: _lineArr[0],
        zoom: 17,
      });
    }

    if (curMaker) {
      map.remove(curMaker);
    }

    if (polyline) {
      map.remove(polyline);
    }

    if (passedPolyline) {
      map.remove(passedPolyline);
    }

    curMaker = new window.AMap.Marker({
      map,
      position: _lineArr[0],
      icon: 'https://webapi.amap.com/images/car.png',
      offset: new window.AMap.Pixel(-26, -13),
      autoRotation: true,
      angle: -90,
    });

    // 绘制轨迹
    polyline = new window.AMap.Polyline({
      map,
      path: _lineArr,
      showDir: true,
      strokeColor: '#28F', // 线颜色
      // strokeOpacity: 1,     //线透明度
      strokeWeight: 6, // 线宽
      // strokeStyle: "solid"  //线样式
    });

    passedPolyline = new window.AMap.Polyline({
      map,
      strokeColor: '#AF5', // 线颜色
      // strokeOpacity: 1,     //线透明度
      strokeWeight: 6, // 线宽
      // strokeStyle: "solid"  //线样式
    });

    curMaker.on('moving', (e) => {
      passedPolyline.setPath(e.passedPath);
    });

    map.setFitView();

    curMaker.moveAlong(_lineArr, 400);
  };

  watch(
    () => props.lineArr,
    (newVal) => {
      lineArrLocal = newVal || [];
      if (window.AMap) {
        setLineAni(newVal);
      }
    }
  );

  onMounted(() => {
    if (window.AMap) {
      setLineAni(lineArrLocal);
    } else {
      initMapFile()
        .then((res) => {
          window.AMap = res;
          setLineAni(lineArrLocal);
        })
        .catch((e) => {
          console.log(e);
        });
    }
  });

  onUnmounted(() => {
    map?.destroy();
  });
</script>

<style lang="less">
  #map-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
</style>
